import fs from 'fs'; import path from 'path'; import Yaml from 'yaml';

export const PLUGIN_PATH = path.join(path.resolve(), 'plugins', 'Bread-Shop');
const FILE_PATH = {
    player: path.join(PLUGIN_PATH, 'data', 'player'),
    config: path.join(PLUGIN_PATH, 'config.yaml')
};

/** 读取玩家数据 */
export async function getPlayerData(GROUP_ID, ID) {
    const DATA = await JSON.parse(fs.readFileSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json'), 'utf8'))
    return DATA
}

/** 存储玩家数据 */
export function storagePlayerData(GROUP_ID, ID, DATA) {
    fs.writeFileSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json'), JSON.stringify(DATA, null, 4));
}

/** 存储配置数据 */
export function storageConfigrData(DATA) {
    fs.writeFileSync(FILE_PATH['config'], Yaml.stringify(DATA), 'utf8')
}

/** 判断玩家是否存在 */
export function isPlayerExist(GROUP_ID, ID) {
    if (fs.existsSync(path.join(FILE_PATH['player'], GROUP_ID.toString(), ID + '.json'))) {
        return true
    }
    return false
}

/** 判断群是否存在 */
export function isGroupExist(GROUP_ID) {
    if (fs.existsSync(path.join(FILE_PATH['player'], GROUP_ID.toString().toString()))) {
        return true
    }
    return false
}

/** 读取配置 */
export async function readConfiguration() {
    const DATA = Yaml.parse(fs.readFileSync(FILE_PATH['config'], 'utf-8'))
    return DATA
}

/** 创建群文件夹 */
export function createAGroupFolder(GROUP_ID) {
    fs.mkdirSync(path.join(FILE_PATH['player'], GROUP_ID.toString()), { recursive: true })
}

/** 将时间戳转换为秒 */
export function timestampToSeconds(TIMESTAMP) {
    return Math.floor(TIMESTAMP / 1000);
}

/** 秒转换为分钟和秒 */
export function convertSecToMinAndSec(seconds) {
    let minutes = Math.floor(seconds / 60);
    let remainingSeconds = seconds % 60;
    return { minutes, remainingSeconds };
}

/** 当前日期 */
export function getCurrentDate() {
    return new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })
}

/** 读取群文件夹用户列表 */
export function getGroupPlayerList(GROUP_ID) {
    return fs.readdirSync(path.join(FILE_PATH['player'], GROUP_ID.toString()))
}

/** 读取群列表 */
export function getGroupList() {
    return fs.readdirSync(FILE_PATH['player'])
}